<template>
	<div class="system-managerUser-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-managerUser-search mb15">
        <el-button size="default" type="primary" class="ml10" @click="getTableData()">
          <el-icon>
            <ele-Search />
          </el-icon>
          刷新
        </el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAddManagerUser('add')">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					添加管理员用户
				</el-button>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="username" label="账号" width="150" show-overflow-tooltip></el-table-column>
				<el-table-column prop="nickName" label="姓名" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="userMobile" label="电话号码" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="orgName" label="所在机构" width="200" show-overflow-tooltip></el-table-column>
<!--        <el-table-column prop="userRole" label="角色" width="300" show-overflow-tooltip></el-table-column>-->
        <el-table-column prop="userRoleCodes" label="角色" width="300" show-overflow-tooltip></el-table-column>
				<el-table-column prop="isDelete" label="状态" width="100" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.isDelete==0">正常</el-tag>
						<el-tag type="info" v-else>禁用</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip></el-table-column>
				<el-table-column prop="gmtModified" label="修改时间" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" width="200">
					<template #default="scope">
              <el-button  size="small" text type="primary" @click="onOpenAuthorizeDialog(scope.row.id)" >授权管理</el-button>
              <el-button  size="small" text type="primary" @click="onOpenEditAddManagerUser('edit', scope.row)" >修改信息</el-button>
              <el-button :disabled="scope.row.isDelete === 1" size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 50]"
				v-model:current-page="state.tableData.param.current"
				background
				v-model:page-size="state.tableData.param.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>
    <ManagerDialog ref="ManagerDialogRef" @refresh="getTableData()" />
    <authorizeDialog ref="authorizeDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemManagerUser">
import {reactive, onMounted, defineAsyncComponent, ref} from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {userApi} from "/@/api/user";

const {managerListByPage,managerRemoveById} = userApi();
const ManagerDialog = defineAsyncComponent(() => import('/src/views/system/managerUser/dialogManager.vue'));
const ManagerDialogRef = ref();
const authorizeDialog = defineAsyncComponent(() => import('/src/views/system/noRole/authorizeDialog.vue'));
const authorizeDialogRef = ref();

const state = reactive<ManagerSysUserState>({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			current: 1,
			pageSize: 10,
		},
	},
});
const userTypeMap: { [key: string]: string } = {
  OPERATION_MANAGER: '运营管理人员',
  STUDENT: '学生',
  TEACHER: '普通教师',
  TEACHER_MANAGER: '教师管理员',
  STAFF: '工作人员',
  PARENT: '家长',
  LEADER: '教育局管理员',
  SCHOOL_MANAGER: '学校管理员',
  DEVELOPER: '开发或运维人员',
  BOE_LEADER: '教育局领导',
  BOE_DEPARTMENT_HEAD: '部门负责人',
  BOE_DEPARTMENT_STAFF: '部门工作人员',
  BOE_SCHOOL_HEAD: '校长',
  BOE_SCHOOL_DIRECTOR: '办公室主任'
};
const onOpenAddManagerUser = (type: string) => {
  ManagerDialogRef.value.openDialog(type);
};


const onOpenEditAddManagerUser = (type: string, row: RowManagerUserType) => {
  ManagerDialogRef.value.openDialog(type,row);
};

const onOpenAuthorizeDialog = (userId: string) => {
  authorizeDialogRef.value.openDialog(userId);
};

// 转换 userRole 为码值
const convertUserRolesToCodes = (data: RowManagerUserType[]) => {
  return data.map(user => {
    const userRoles = user.userRoles // 假设 userRole 是以逗号分隔的字符串
    const roleCodes = userRoles.map(role => userTypeMap[role] || role); // 转换为码值，如果找不到则保持原值
    return {
      ...user,
      userRoleCodes: roleCodes.join(', '), // 将码值数组转换为字符串
    };
  });
};
// 初始化表格数据
const getTableData = async () => {
  state.tableData.loading = true;
  const res = await managerListByPage(state.tableData.param)
  if (res.status === 200) {
    console.log(res.data)
    state.tableData.data = convertUserRolesToCodes(res.data.records);
    state.tableData.total = res.data.total;
    state.tableData.loading = false;
  }


};


// 删除用户
const onRowDel = (row: RowManagerUserType) => {
	ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.nickName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
      const res = await managerRemoveById({id: row.id})
      if (res.status === 200) {
        await getTableData();
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败');
      }
    })
		.catch(() => {});
};


// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getTableData();
};
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>

<style scoped lang="scss">
.system-managerUser-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>
